#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : lee

import sys
import os
import logging
import re
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CfxPgYetiTextureCheck(CheckBase):
    # 初始化检查属性表
    import_types_attr_lib = {0: "inputGeometry", 1: "inputStrandData", 2: "guideSets"}

    def __init__(self):
        super(CfxPgYetiTextureCheck, self).__init__()

    def check_pgYeti_node_attrs(self):
        """
        描述：pgYeti节点检查的启动函数
        """
        error_nodes = []
        error_nodes_data = {}
        for yeti_node in cmds.ls(type="pgYetiMaya"):
            # 检查Texture节点属性是否准确
            graph_node, texture_check_result = self.check_pgYeti_texture_attrs(yeti_node)
            if not texture_check_result:
                error_nodes.append(yeti_node)
                file_name = cmds.pgYetiGraph(yeti_node, node=graph_node, param="file_name", getParamValue=True)
                error_nodes_data[yeti_node] = {graph_node: file_name}
                continue

        return error_nodes, error_nodes_data

    def check_pgYeti_texture_attrs(self, node):
        image_search_path = cmds.getAttr(node + ".imageSearchPath")
        for graph_node in cmds.pgYetiGraph(node, listNodes=True):
            node_type = cmds.pgYetiGraph(node, node=graph_node, nodeType=True)
            if node_type == "texture":
                file_name = cmds.pgYetiGraph(node, node=graph_node, param="file_name", getParamValue=True)
                file_name = file_name.replace("<UDIM>", "\d+")
                texture_file = ""
                if '/' in file_name and ':' in file_name:
                    log.warning(u'请将这个节点:%s->%s,改成相对路径' % (node, graph_node))
                    return graph_node, False
                if not os.path.exists(image_search_path):
                    log.warning(u'不存在这个路径:%s' % image_search_path)
                    break
                for name in os.listdir(image_search_path):
                    if re.search(file_name, name):
                        texture_file = os.path.join(image_search_path, name)
                        break
                if not texture_file:
                    return graph_node, False
        return node, True

    def check_pgYeti_root_node(self, node):
        root_node = cmds.pgYetiGraph(node, getRootNode=True)
        if not root_node:
            return False
        if cmds.pgYetiGraph(node, node=root_node, outputNodeCount=True) > 0:
            return False
        return True

    def check(self):
        result_proc, error_nodes_data = self.check_pgYeti_node_attrs()
        if result_proc:
            error_nodes_message = u""
            for node in error_nodes_data:
                error_nodes_message += node + u"的"
                for graph_node in error_nodes_data[node]:
                    error_nodes_message += graph_node + u"文件名为%s不存在\n" % error_nodes_data[node][graph_node]
            result_log = u'Error:报错节点为%s\n, yeti信息为%s\n' % (result_proc, error_nodes_message)
        else:
            result_log = u'Succeed:没有问题\n'

        return result_log

    def fix(self):
        pass
